/**
 * @Description ProductPriceImpController.java
 * @author xu_cc [18724000100@163.com]
 * @date 创建时间：2017年9月26日 下午3:58:54
 */
package com.solution.admin.product.controller;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.solution.admin.customer.entity.CustomerLevelEntity;
import com.solution.admin.customer.service.CustomerLevelService;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.entity.ProductPriceEntity;
import com.solution.admin.product.service.ProductPriceService;
import com.solution.admin.product.service.ProductService;
import com.solution.common.controller.BaseController;
import com.solution.common.utils.importExcel.ExcelUtil;
import com.solution.common.utils.string.StringUtil;

@RequestMapping("/productPrice")
@Controller
public class ProductPriceImpController extends BaseController {

	Logger logger = LoggerFactory.getLogger(ProductPriceImpController.class);

	@Autowired
	ProductPriceService productPriceService;

	@Autowired
	ProductService productService;
	@Autowired
	private CustomerLevelService customerLevelService;

	/**
	 * 页面跳转
	 * 
	 * @param request
	 * @param model
	 * @return String
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年9月26日 下午4:49:34
	 */
	@RequestMapping("/productPriceImpPage")
	public String toProductPricePage(HttpServletRequest request, Model model) {

		return "product/productPrice_imp";
	}

	/**
	 * 验证文件
	 * 
	 * @param file
	 * @param model
	 * @return boolean
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年9月26日 下午6:05:53
	 */
	private boolean doCheck(MultipartFile file, Model model) {
		if (null == file) {
			model.addAttribute("msg", "<font style=\"color:red;\">未获取到传入文件内容！</font>");
			return false;
		}
		if (!file.getOriginalFilename().matches("^.+\\.(?i)(xlsx)$") && !file.getOriginalFilename().matches("^.+\\.(?i)(xls)$")) {
			model.addAttribute("msg", "<font style=\"color:red;\">请传入xlsx 或 xls格式的文件！</font>");
			return false;
		}
		if (file.getSize() == 0) {
			model.addAttribute("msg", "<font style=\"color:red;\">错误文件(可能是非Excel文件改后缀名导致)！</font>");
			return false;
		}
		if (file.getSize() > (2 * 1048576)) {
			model.addAttribute("msg", "<font style=\"color:red;\">文件大小限制为2M！！</font>");
			return false;
		}
		return true;
	}

	@RequestMapping("/impPrice")
	public String doImpPrice(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile multfile, Model model) {
		model.addAttribute("step", 3);
		try {
			int success = 0;
			int failed = 0;
			if (doCheck(multfile, model)) {
				// 失败商品
				String productIdStr = "";
				StringBuffer error = new StringBuffer();
				List<Map<String, String>> mapList = null;
				try {
					// 先以xlsx，poi读取2007的方式读取
					mapList = ExcelUtil.readSheet2007(multfile, 0);
					if (null == mapList) {
						// 以2003，xls，jxl的方式读取
						File file = ExcelUtil.multipartToFile(multfile);
						mapList = ExcelUtil.readSheet(file, 0);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (null != mapList && mapList.size() > 0) {
					// 读取到的title
					Map<String, String> titleMap = mapList.get(0);
					// 正常title
					Map<String, String> headMap = new HashMap<String, String>();
					headMap.put("商品编码", "商品编码");
					headMap.put("商品名称", "商品名称");
					headMap.put("基价", "基价");
					headMap.put("市场价", "市场价");
					headMap.put("成本价", "成本价");
					headMap.put("最低限价", "最低限价");
					// 字典map（key=级别名称，value=级别值）
					Map<String, String> keyDataMap = new HashMap<String, String>();
					// List<KeyMapEntity> keyMaplist =
					// keyMapService.listKeyMap("level");
					// for (KeyMapEntity keyMap : keyMaplist) {
					// headMap.put(keyMap.getKeyIntro(), keyMap.getKeyValue());
					// keyDataMap.put(keyMap.getKeyIntro(),
					// keyMap.getKeyValue());
					// }
					Map<String, Object> param = new HashMap<String, Object>();
					List<CustomerLevelEntity> levelList = customerLevelService.listEbCustomerLevel(param);
					for (CustomerLevelEntity cusLevel : levelList) {
						String levelId = String.valueOf(cusLevel.getId());
						headMap.put(cusLevel.getLevelName(), levelId);
						keyDataMap.put(cusLevel.getLevelName(), levelId);
					}
					if (titleMap.size() != headMap.size()) {
						model.addAttribute("msg", "标题校验失败，请上传正确的文件");
						return "product/productPrice_imp";
					}
					for (String key : headMap.keySet()) {
						if (!titleMap.containsKey(key)) {
							model.addAttribute("msg", "标题校验失败");
							return "product/productPrice_imp";
						}
					}
					// 数据抽取及组装
					// 价格集合
					List<ProductPriceEntity> proPriceList = null;
					Map<String, Object> paramMap = null;// 查询商品的参数
					// 需要修改的商品集合
					List<Map<String, ProductEntity>> modMapList = new ArrayList<Map<String, ProductEntity>>();
					for (int i = 0; i < mapList.size(); i++) {
						ProductEntity product = null;
						// 获取数据
						Map<String, String> map = mapList.get(i);
						// 组装查询参数
						paramMap = new HashMap<String, Object>();
						String productCode = map.get("商品编码");
						String productName = map.get("商品名称");
						try {
							if (StringUtil.isNotNull(productCode) && StringUtil.isNotNull(productName)) {
								paramMap.put("productCode", productCode);
								List<ProductEntity> proList = productService.listProduct(paramMap);
								if (null != proList && proList.size() > 0) {
									product = proList.get(0);
								} else {
									error.append("第").append(i + 1).append("行匹配不到商品，商品编码：").append(productCode).append("，商品名称：").append(productName)
									        .append("。<br/>");
									continue;
								}
							} else {
								error.append("第").append(i + 1).append("行数据输入异常，商品编码和商品名称都不可为空。<br/>");
								continue;
							}
							// excel中的基价
							BigDecimal basePrice = new BigDecimal(map.get("基价"));
							BigDecimal marketPrice = new BigDecimal(map.get("市场价"));
							BigDecimal simulationPrice = new BigDecimal(map.get("成本价"));
							BigDecimal lowestPrice = new BigDecimal(map.get("最低限价"));
							// 获取价格集合
							try {
								proPriceList = doFullData(product.getId(), map, keyDataMap, basePrice);
							} catch (Exception ex) {
								error.append("第").append(i + 2).append("行数据输入异常；").append(ex.getMessage()).append("<br/>");
								continue;
							}
							ProductEntity newProduct = new ProductEntity();
							newProduct.setId(product.getId());
							newProduct.setBasePrice(basePrice);
							newProduct.setMarketPrice(marketPrice);
							newProduct.setSimulationPrice(simulationPrice);
							newProduct.setLowestPrice(lowestPrice);
							newProduct.setMarketPriceLevel("");
							newProduct.setSimulationPriceLevel("");
							newProduct.setModifier(getUserName());
							// 价格集合
							newProduct.setProductPriceList(proPriceList);
							// 填充需要修改map
							Map<String, ProductEntity> modMap = new HashMap<String, ProductEntity>();
							modMap.put("product", product);
							modMap.put("newProduct", newProduct);
							modMapList.add(modMap);
						} catch (Exception e) {
							error.append("第").append(i + 2).append("行数据输入异常，请检查数据是否全部输入正确！商品编码：").append(productCode).append("，商品名称：").append(productName).append("。<br/>");
							e.printStackTrace();
						}
					}
					// 错误信息为空不改
					if (StringUtil.isNotNull(error.toString())) {
						model.addAttribute("error", error.toString());
						model.addAttribute("step", 3);
						return "product/productPrice_imp";
					} else {
						if (modMapList.size() > 0) {
							productService.updateProductPrice(modMapList);
							model.addAttribute("msg", error.append("商品价格数据导入成功" + modMapList.size() + "条！"));
						} else {
							model.addAttribute("error", error.append("未解析到可修改的数据！"));
						}
						model.addAttribute("step", 3);
					}
					return "product/productPrice_imp";
				} else {
					model.addAttribute("msg", "无法读取到数据");
					return "product/productPrice_imp";
				}
			} else {
				return "product/productPrice_imp";
			}
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "数据导入异常！");
			return "product/productPrice_imp";
		}
	}

	/**
	 * 获取价格集合
	 * 
	 * @Title: doFullData
	 * @Description:(描述)
	 * @param id
	 * @param map
	 *            （行数据）
	 * @param keyDataMap
	 *            （取值模板）
	 * @return List<ProductPriceEntity>
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月15日 下午6:21:09
	 */
	private List<ProductPriceEntity> doFullData(Long id, Map<String, String> map, Map<String, String> keyDataMap, BigDecimal basePrice) throws Exception {
		List<ProductPriceEntity> productPriceList = new ArrayList<ProductPriceEntity>();
		StringBuffer error = new StringBuffer();
		for (Map.Entry<String, String> entry : keyDataMap.entrySet()) {
			// 获取单元格值，如果有，说明是正常的价格值
			String cellValue = map.get(entry.getKey());
			BigDecimal cellDiffPrice = BigDecimal.ZERO;
			if (StringUtil.isNotNull(cellValue)) {
				try {
					cellDiffPrice = new BigDecimal(cellValue);
					/*// 结果是:-1 小于,0 等于,1 大于
					if(cellDiffPrice.compareTo(basePrice) == 1) {
						error.append("商品编码：").append(map.get("商品编码")).append("商品名称：").append(map.get("商品名称")).append("的列：").append(entry.getKey())
				        .append(" 价格浮动不可大于基价！<br/>");
					}*/
				} catch (Exception e) {
					logger.error("获取价格异常，商品编码：{}，商品名称：{}，列名：{}", map.get("商品编码"), map.get("商品名称"), entry.getKey());
					e.printStackTrace();
				}
			} else {
				error.append("商品编码：").append(map.get("商品编码")).append("商品名称：").append(map.get("商品名称")).append("的列：").append(entry.getKey())
				        .append(" 未输入正确值！<br/>");
			}
//			// 计算差异价格（减基价）
//			BigDecimal diffPrice = null;
//			if (null == cellDiffPrice) {
//				diffPrice = BigDecimal.ZERO;
//			} else {
//				diffPrice = cellDiffPrice;
//			}
			ProductPriceEntity productPrice = new ProductPriceEntity();
			productPrice.setProductId(id);
			productPrice.setPriceLevel(entry.getValue());
			productPrice.setDiffPrice(cellDiffPrice);
			productPrice.setModifier(getUserName());
			productPriceList.add(productPrice);
		}
		if (error.toString().length() > 0) {
			throw new Exception(error.toString());
		}
		return productPriceList;
	}

	/**
	 * 导出
	 * 
	 * @param request
	 * @param response
	 *            void
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年9月26日 下午4:49:37
	 */
	@RequestMapping("/exportTemp")
	public void exportOrder(HttpServletRequest request, HttpServletResponse response, String productIdStr) {
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			List<CustomerLevelEntity> levelList = customerLevelService.listEbCustomerLevel(paramMap);
			// List<KeyMapEntity> keyMaplist =
			// keyMapService.listKeyMap("level");
			List<String> headNames = new ArrayList<String>();
			headNames.add("商品编码");
			headNames.add("商品名称");
			headNames.add("基价");
			headNames.add("市场价");
			headNames.add("成本价");
			headNames.add("最低限价");
			for (CustomerLevelEntity cusLevel : levelList) {
				headNames.add(cusLevel.getLevelName());
			}
			// for (KeyMapEntity keyMap : keyMaplist) {
			// headNames.add(keyMap.getKeyIntro());
			// }
			// 参数
			List<Long> idLst = null;
			if (StringUtil.isNotNull(productIdStr)) {
				idLst = new ArrayList<Long>();
				String[] idStr = productIdStr.split(",");
				for (int i = 0; i < idStr.length; i++) {
					try {
						idLst.add(Long.parseLong(idStr[i]));
					} catch (Exception e) {
						continue;
					}
				}
			}
			List<ProductEntity> list = productPriceService.getProPriceExpList(idLst);
			List<Map<String, Object>> dataMap = null;

			if (null != list && list.size() > 0) {
				dataMap = new ArrayList<Map<String, Object>>();
				for (ProductEntity product : list) {
					Map<String, Object> proMap = new HashMap<String, Object>();
					proMap.put("productCode", product.getProductCode());
					proMap.put("productName", product.getProductName());
					proMap.put("basePrice", product.getBasePrice());
					proMap.put("marketPrice", product.getMarketPrice());
					proMap.put("simulationPrice", product.getSimulationPrice());
					proMap.put("lowestPrice", product.getLowestPrice());

					if (StringUtil.isNotNull(product.getPriceLevelStr()) && StringUtil.isNotNull(product.getDiffPriceStr())) {
						String[] priceLevelArr = product.getPriceLevelStr().split(",");
						String[] diffPriceArr = product.getDiffPriceStr().split(",");
						for (int i = 0; i < priceLevelArr.length; i++) {
							String level = priceLevelArr[i];
							BigDecimal diffPrice = null;
							try {
								diffPrice = new BigDecimal(diffPriceArr[i]);
							} catch (Exception e) {
								diffPrice = new BigDecimal(0);
							}
							proMap.put(level, diffPrice);
						}
					}
					dataMap.add(proMap);
				}
			}
			List<String> fieldNames = new ArrayList<String>();
			fieldNames.add("productCode");
			fieldNames.add("productName");
			fieldNames.add("basePrice");
			fieldNames.add("marketPrice");
			fieldNames.add("simulationPrice");
			fieldNames.add("lowestPrice");
			// for (KeyMapEntity keyMap : keyMaplist) {
			// fieldNames.add(keyMap.getKeyValue());
			// }
			for (CustomerLevelEntity cusLevel : levelList) {
				fieldNames.add(String.valueOf(cusLevel.getId()));
			}

			expToExcel07(request, response, headNames, fieldNames, "ProductPriceTemp.xlsx", dataMap);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
